const express = require("express");
const PostModel = require("../models/post");
const router = express.Router();

// 文章列表页面
router.get("/", async (req, res) => {
  // 1. 获取pageNum与pageSize参数
  let pageNum = parseInt(req.query.pageNum) || 1;
  let pageSize = parseInt(req.query.pageSize) || 5;

  // 2. 获取文章总条数,并计算总页数
  const count = await PostModel.find().countDocuments();
  const totalPages = Math.ceil(count / pageSize);

  // 3. 查询当前页的文章
  const posts = await PostModel.find()
    .populate("user")
    .populate("pictures")
    .skip((pageNum - 1) * pageSize)
    .limit(pageSize)
    .sort({ updatedAt: -1 });

  console.log(posts);

  // 4. 响应
  res.render("post/index", { posts, pageNum, totalPages });
});

// 文章创建页面
router.get("/create", (req, res) => {
  res.render("post/create");
});

// 文章创建动作
router.post("/", async (req, res) => {
  let title = req.body.title;
  let content = req.body.content;
  let picturesStr = req.body.pictures;
  let pictures = picturesStr ? picturesStr.split(",") : [];
  const post = new PostModel({ title, content, pictures, user: req.user._id });
  await post.save();

  res.redirect(`/posts/${post._id}`);
});

// 文章详情页面
router.get("/:id", async (req, res) => {
  const id = req.params.id;
  const post = await PostModel.findById(id).populate("pictures");
  console.log(post);
  res.render("post/show", { post });
});

// 文章编辑页面
router.get("/:id/edit", (req, res) => {
  res.render("post/edit");
});

module.exports = router;
